package com.example.javaproject.jvm;

/**
 * Description:代码演示了2点
 * 1、对象可以在Gc时自救
 * 2、这种自救机会只有一次，因为一个对象点finilize()方法最多只会被系统调用一次
 * <br/>Author:  tianjinyong
 * <br/>Date:    2020/5/11 11:28 PM
 */
public class FinalizeEscapeGc {
    public static FinalizeEscapeGc SAVE_HOOK = null;

    public void isAlive() {
        System.out.println("yes, i am still alive");
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("finalize method invoked");
        SAVE_HOOK = this;
    }

    public static void main(String[] args) throws Throwable {
        SAVE_HOOK = new FinalizeEscapeGc();

        //对象第一次自我拯救
        SAVE_HOOK = null;
        System.gc();
        //因为finalize方法优先级很低，所以暂停0.5s等待它去执行finalize()方法
        Thread.sleep(500);
        if (SAVE_HOOK != null) {
            SAVE_HOOK.isAlive();
        } else {
            System.out.println("no, i am dead");
        }

        //下面这段代码和上面完全一样，但这次自我拯救救失败了
        SAVE_HOOK = null;
        System.gc();
        //因为finalize方法优先级很低，所以暂停0.5s等待它去执行finalize()方法
        Thread.sleep(500);
        if (SAVE_HOOK != null) {
            SAVE_HOOK.isAlive();
        } else {
            System.out.println("no, i am dead");
        }
    }

}
